<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模块名称" prop="moduleName">
        <el-input
            v-model="queryParams.moduleName"
            placeholder="请输入模块名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完成状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择完成状态" clearable>
          <el-option
              v-for="dict in sys_module_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:module:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:module:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:module:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:module:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading"
              :data="moduleList"
              row-key="moduleId"
              :expand-row-keys="expandRows"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              default-expand-all
              @selection-change="handleSelectionChange"
              @expand="handleExpand"
              @collapse="handleCollapse"
              @expand-change="handleExpandChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模块ID" align="center" prop="moduleId" />
      <el-table-column label="模块名称" align="center" prop="moduleName">
        <template #default="scope">
          <div style="display: flex; align-items: center;">
            <el-button
                v-if="scope.row.children && scope.row.children.length"
                type="text"
                @click.stop="toggleExpand(scope.row)"
                style="font-size: 12px; font-weight: bold;"
            >
              {{ scope.row.moduleName }}
            </el-button>
            <span v-else>{{ scope.row.moduleName }}</span>
          </div>
<!--          <span :style="{ marginLeft: `${scope.row.level * 20}px` }">{{ scope.row.moduleName }}</span>-->
        </template>
      </el-table-column>
      <el-table-column label="完成状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_module_state" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:module:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:module:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改模块对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="moduleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="form.moduleName" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="完成状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择完成状态">
            <el-option
                v-for="dict in sys_module_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="父级模块" prop="parentId">
          <el-cascader
              v-model="form.parentId"
              :options="moduleOptions"
              :props="{ checkStrictly: true, value: 'moduleId', label: 'moduleName' }"
              clearable
              placeholder="请选择父级模块"
              @change="handleParentChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Module">
import { ref, reactive, toRefs, onMounted } from 'vue';
import { listModule, getModule, delModuleWithChildren, addModule, updateModule } from "@/api/system/module";
import { useDict } from '@/utils/dict';
import { getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const { sys_module_state } = useDict('sys_module_state');

const moduleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const moduleOptions = ref([]);
const expandRows = ref([]);

const data = reactive({
  form: {
    moduleId: null,
    moduleName: null,
    status: null,
    remark: null,
    parentId: null // 新增 parentId 字段
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    moduleName: null,
    status: null,
  },
  rules: {
    moduleName: [
      { required: true, message: "模块名称不能为空", trigger: "blur" }
    ],
  },
  moduleMap: {} // 添加 moduleMap
});

const { queryParams, form, rules, moduleMap } = toRefs(data);

// 加载所有模块选项，用于 cascader
function loadModuleOptions() {
  listModule({}).then(response => {
    const { tree, map } = buildTree(response.rows);
    moduleOptions.value = tree;
    moduleMap.value = map; // 存储模块映射
  });
}
// 切换展开/折叠状态的方法
function toggleExpand(row) {
  const idNow = row.moduleId;
  if (typeof idNow === 'string') {
    const index = expandRows.value.indexOf(idNow);
    if (index > -1) {
      // 如果存在，则删除
      expandRows.value.splice(index, 1);
    } else {
      // 如果不存在，则添加
      expandRows.value.push(idNow);
    }
  }
}
function handleExpandChange(row, expandedRows) {
  // 这里可以添加你想要执行的逻辑
  console.log('Expanded Rows:', expandedRows);
}
function buildTree(modules) {
  const map = {};
  modules.forEach(module => {
    map[module.moduleId] = { ...module, children: [] };
  });

  const tree = [];
  modules.forEach(module => {
    if (module.parentId === null || !map[module.parentId]) {
      tree.push(map[module.moduleId]);
    } else {
      map[module.parentId].children.push(map[module.moduleId]);
    }
  });

  return { tree, map };
}

// 查询模块列表
function getList() {
  loading.value = true;
  listModule(queryParams.value).then(response => {
    const { tree, map } = buildTree(response.rows);
    moduleList.value = tree;
    // moduleList.value = response.rows.map(item => ({
    //   ...item,
    //   level: calculateLevel(item, map),
    //   hasChildren: item.children && item.children.length > 0
    // }));
    total.value = response.total;
    loading.value = false;
  });
}

function calculateLevel(item, map) {
  let level = 0;
  while (item.parentId !== null && map[item.parentId]) {
    item = map[item.parentId];
    level++;
  }
  return level;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 展开/折叠事件处理
function handleExpand(row, column) {
  console.log('Expand', row, column);
}
function handleCollapse(row, column) {
  console.log('Collapse', row, column);
}
// 表单重置
function reset() {
  form.value = {
    moduleId: null,
    moduleName: null,
    status: null,
    remark: null,
    parentId: null
  };
  proxy.resetForm("moduleRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.moduleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加模块";
  form.value.parentId = null; // 默认不设置父级模块
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const _moduleId = row.moduleId || ids.value;
  getModule(_moduleId).then(response => {
    form.value = response.data;
    form.value.parentId = response.data.parentId ? [response.data.parentId] : null;
    open.value = true;
    title.value = "修改模块";
  });
}

// 提交按钮
// 提交按钮
function submitForm() {
  proxy.$refs["moduleRef"].validate(valid => {
    if (valid) {
      // 处理 parentId，确保它是 Long 类型或 null
      const submitData = { ...form.value };
      if (Array.isArray(submitData.parentId)) {
        submitData.parentId = submitData.parentId.length > 0 ? submitData.parentId[submitData.parentId.length - 1] : null;
      }

      if (submitData.moduleId != null) {
        updateModule(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        if (submitData.parentId !== null) {
        addModule(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      } else {
          addModule(submitData).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  const _moduleIds = row.moduleId || ids.value;

  proxy.$modal.confirm('是否确认删除模块编号为"' + _moduleIds + '"的数据项及其所有子模块？').then(function () {
    return delModuleWithChildren(_moduleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 导出按钮操作
function handleExport() {
  proxy.download('system/module/export', {
    ...queryParams.value
  }, `module_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  loadModuleOptions(); // 加载模块选项
});

// 处理父级模块变化时重置模块 ID（如果选择了顶级模块）
function handleParentChange(value) {
  if (!value.length) {
    form.value.parentId = null;
  } else {
    form.value.parentId = value[value.length - 1];
  }
}
</script>